# -*- encoding: utf-8 -*-
from src.ApiTest.Operating.Database.operating_database import OperatingConfig, MysqlConfigSchema
from src.User.Database.user_database import User, UserSchema
from Common.yaml_method import YamlMethod
import ast


class OperatingList:
    """
    获取运行配置列表接口
    """

    @staticmethod
    def operating_list(page, limit, user_id, project_name):
        """
        获取运行配置列表接口
        :param page: 页码
        :param limit: 每页多少条数据
        :param user_id: user_id
        :param project_name: 项目名称
        :return:
        """

        code = YamlMethod().read_data('code.yaml')['code']

        if project_name:
            data = OperatingConfig.query.filter_by(projectName=project_name).paginate(page=page, per_page=limit)
        else:
            # 先查询用户所属项目信息
            user = User.query.filter_by(id=user_id).first()
            user_schema = UserSchema()
            user_data = user_schema.dump(user)
            user_project_id = user_data['user_projects']
            id_list = ast.literal_eval(user_project_id)
            data = OperatingConfig.query.filter(OperatingConfig.projectId.in_(id_list)).\
                paginate(page=page, per_page=limit)

        info = []
        if data:
            for i in data.items:
                mysql_schema = MysqlConfigSchema()
                mysql_data = mysql_schema.dump(i)
                # 将单条信息添加到info中
                info.append(mysql_data)

        total = data.total
        res = {
            'code': code[0],
            'message': 'success',
            'data': {
                'operatingList': info,
                'total': total
            }
        }

        return res

